package com.rentapark.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gcm.GCMRegistrar;

import data.DB;


/*this activity runs only the first time the user enters the application
 * here the user enter all the data the system needs and then the information is sent to the server
 * in order to be saved in the system's data base
 */
public class SignUp extends Activity{
	static final int PROGRESS_DIALOG = 0;
	ProgressDialog progressDialog;
	String name;
	String idString;
	String phone;
	String car_no;
	String second;
	final SignUp thisActivity = this;
	DB db_instance;

//handles server's response	
	private final Handler handler = new Handler() {  
		public void handleMessage(Message msg) { 
			progressDialog.dismiss(); 
			Log.d("NewUSER","got response");
			String bundleResult = msg.getData().getString("RESPONSE"); 
			SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
			//once the user signed up the user's id is saved in the preferences file
			SharedPreferences.Editor ed = ref.edit();
			ed.putString("my_id", idString);
			ed.commit();
			//the user has already signed up and logged in.
//			db_instance.login=true;
			//after the user signed up, the "MainScreen" activity is started
			Intent intent = new Intent(thisActivity, MainScreen.class); 
			startActivity(intent);
		} 
	}; 
	
	//onCreate method
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signup);
		second="0";
		//getting db instance
		db_instance=DB.getInstance();
		
		//sign up button- when the user press this button, all the info he entered is saved in the local DB
		Button AddItemButton = (Button)this.findViewById(R.id.AddItemButton);
		AddItemButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final EditText nameText = (EditText) findViewById(R.id.EditText01);
				final EditText idText=(EditText) findViewById(R.id.EditText02);
				final EditText phoneText=(EditText) findViewById(R.id.EditText03);
				final EditText car_noText=(EditText) findViewById(R.id.EditText04);

								
				name = nameText.getText().toString();
				idString=idText.getText().toString();
				phone=phoneText.getText().toString();
				car_no=car_noText.getText().toString();
				//saving all user's data in applicaiton file
				SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
				SharedPreferences.Editor ed = ref.edit();
				ed.putString("my_id", idString);
				ed.putString("userName", name);
				ed.putString("userPhone", phone);
				ed.putString("UserCarNo", car_no);
				
				ed.commit();
				
				//saving all user's data in local DB
				db_instance.userID=Double.parseDouble(idString);
				db_instance.userName=name;
				db_instance.userPhone=phone;
				db_instance.UserCarNo=car_no;

				Log.d("sign up","success");
				Intent intent = new Intent(thisActivity, MainScreen.class); 
				startActivity(intent);
				//perform sign up and login
				performRequest();


			}


		});
	}
	/*
	 * this method send an htttp post message to the server with all the user's information
	 */
	private void performRequest() { 
		// create HTTP response handler to handle the HTTP response
		// the response data is extracted from the HTTP message and then it is wrapped in a message
		// which  is passed to the android handler for handling
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    
				//StatusLine status = response.getStatusLine();        
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = data.CommonUtilities.inputStreamToString(entity.getContent());

					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);  
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 

		// start the progress dialog
		this.progressDialog = ProgressDialog.show(this, "executing", "sign up"); 

		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				Log.d("dbURL",db_instance.instanceDNS);
				String url="http://";
				url+=db_instance.instanceDNS;
				url+=":8080/ParkAndLetPark/NewUser";
				Log.d("url is",url);
				HttpPost httppost = new HttpPost(url);
				try {
					try{
						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Response = doc.createElement("MSG_TYPE");
						Response.appendChild(doc.createTextNode("LOGIN"));
						doc.appendChild(Response);
						
						Element type=doc.createElement("LOGIN_TYPE");
						type.appendChild(doc.createTextNode("NEW_USR"));
						Response.appendChild(type);

						Element id=doc.createElement("USER_ID");
						id.appendChild(doc.createTextNode(idString));
						type.appendChild(id);
						
						Element Uname=doc.createElement("USER_NAME");
						Uname.appendChild(doc.createTextNode(name));
						id.appendChild(Uname);

						Element car=doc.createElement("CAR_NO");
						car.appendChild(doc.createTextNode(car_no));
						Uname.appendChild(car);

						Element Uphone=doc.createElement("PHONE_NO");
						Uphone.appendChild(doc.createTextNode(phone));
						car.appendChild(Uphone);

						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString","^^^^^^^^^^^^^^^^^^^^"+xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);
						Log.d("work","post executed");


						String response = httpclient.execute(httppost,responseHandler);
						Log.d("","************************************* "+response);

					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (TransformerConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}




				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}

		}.start(); 
	}
	public void onStop(){
		super.onStop();
		
	}
}


